<template>    
    <div class="systemInfo">
      <span>CPU使用率 : {{ systemInfo.cpu_percent }} %</span>
      <span>GPU使用率 : {{ systemInfo.gpu_percent }} %</span>
      <span>实时检测路数 : {{ systemInfo.run_path_count }} </span>
      <span>内存占用率 : {{ systemInfo.memory_percent }} %</span>
      <span>硬盘剩余容量/总容量 : {{ (systemInfo.disk_free/(1024*1024*1024)).toFixed(2) }} G/{{ (systemInfo.disk_total/(1024*1024*1024)).toFixed(2) }} G</span>
    </div>
    <div class="stopAll">
      <el-button type="danger" @click="stopAll">停止所有检测</el-button>
    </div>
    <el-table 
          max-height="82vh" style="width: 100% ; font-size: 14px "
           border  :row-style="{height: '0'}"
          :stripe=true :fit=true
          @selection-change="handleSelectionChange"
          :data="tableData" 
          highlight-current-row
          ref="singleTableRef">
          <el-table-column prop="path_id" label="DDC通道号" align="center"/>
          <el-table-column prop="status" label="检测状态"  align="center">
            <template #default="scope">
                <el-tag :type="scope.row.status == 3?'success':'danger'">
                  {{ scope.row.status == 3?"进行中":"停止" }}
                </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="collect_column.ch0_freq" label="通道0频点(Hz)"  align="center"/>
          <el-table-column prop="collect_column.ch1_freq" label="通道1频点(Hz)"  align="center"/>
          <el-table-column prop="collect_column.ch2_freq" label="通道2频点(Hz)" align="center"/>
          <el-table-column prop="collect_column.ch3_freq" label="通道3频点(Hz)"  align="center"/>
          <el-table-column prop="collect_column.sample_rate" label="采样率(Hz)"  align="center"/>
          <el-table-column prop="detect_column.detect_bandwidth" label="带 宽(Hz)"  align="center"/>
          <el-table-column prop="detect_column.chid_primary" label="检测通道" width="100rem" align="center"/>
          <el-table-column prop="detect_column.detect_algotype" label="检测算法" align="center">
            <template #default="scope">
              <span v-if="scope.row.detect_column.detect_algotype == 0">能量检测</span>
              <span v-else-if="scope.row.detect_column.detect_algotype == 1">相关检测_5K_DAMA</span>
              <span v-else-if="scope.row.detect_column.detect_algotype == 2">相关检测_25K_DAMA</span>
              <span v-else-if="scope.row.detect_column.detect_algotype == 3">相关检测_CPM</span>
              <span v-else-if="scope.row.detect_column.detect_algotype == 4">相关检测_BPSK</span>
              <span v-else-if="scope.row.detect_column.detect_algotype == 5">相关检测_QPSK</span>
              <span v-else-if="scope.row.detect_column.detect_algotype == 6">相关检测_FSK</span>
            </template>
          </el-table-column>
          <el-table-column prop="stat_column.burst_count" label="突发个数"  align="center"/>
          <el-table-column prop="stat_column.frame_count" label="算法帧数"  align="center"/>
          <el-table-column prop="stat_column.file_count" label="检测个数"  align="center"/>
          <el-table-column prop="estimate_column.estimate_algotype" label="参估算法" align="center">
              <template #default="scope">  
                {{ scope.row.estimate_column.estimate_algotype == 0?"FFT":"自定义" }}
              </template>
          </el-table-column>
          <el-table-column prop="estimate_column.time_range" label="时差范围 (us)" align="center"/>
          <el-table-column prop="estimate_column.freq_range" label="频差范围 (Hz)" align="center"/>
          <el-table-column prop="estimate_column.estimate_bandwidth" label="参估带宽(Hz)"  align="center"/>
          <el-table-column prop="estimate_column.related_len" label="相关长度(ms)"  align="center"/>
          <el-table-column prop="estimate_column.judge_threshold" label="判决门限"  align="center"/>
          <el-table-column prop="estimate_column.up_factor" label="插值倍数"  align="center"/>
          <el-table-column fixed="right" label="操 作" align="center" width="200rem">
            <template #default="scope">
              <el-button round type="danger" size="small" 
                @click="stopOnePath(scope.row.path_id)" :disabled="scope.row.status == 3?false:true">停止</el-button>
              <el-button type="primary" size="small" round
                @click="openDialog('modify',scope.row)" :disabled="scope.row.status == 3?true:false">修改</el-button>
              <el-button round type="success" size="small" 
                @click="startOnePath(scope.row.path_id)" :disabled="scope.row.status == 3?true:false">开始</el-button>
            </template>
          </el-table-column>
    </el-table>
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        :width="dialog.width"
        append-to-body
        center
        draggable="true"
    >
        <el-form
          v-if="dialog.type === 'modify'"
          :model="currentDDC_data"
            label-width="100px"
        >
            <el-form-item label="DDC通道号">
              <p>{{ currentDDC_data.path_id }}</p>
            </el-form-item>
            <el-form-item label="检测通道">
                <el-select v-model="currentDDC_data.detect_column.chid_primary">
                  <el-option 
                    v-for="item in detectChannels"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="检测算法">
                <el-select v-model="currentDDC_data.detect_column.detect_algotype">
                  <el-option 
                    v-for="item in detectAlgorithms"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="检测带宽">
                <el-select v-model="currentDDC_data.detect_column.detect_bandwidth">
                  <el-option 
                    v-for="item in detect_bandwidths"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="参估算法" prop="estimate_algotype">
                <el-select v-model="currentDDC_data.estimate_column.estimate_algotype">
                  <el-option 
                  v-for="item in estimateestimate_algotypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  ></el-option>
                  
                </el-select>
              </el-form-item>
              <el-form-item label="时差范围" prop="time_range">
                <el-input type="number"
                  v-model.number="currentDDC_data.estimate_column.time_range"
                />
              </el-form-item>
              <el-form-item label="频差范围" prop="freq_range">
                <el-input type="number"
                  v-model.number="currentDDC_data.estimate_column.freq_range"
                />
              </el-form-item>
              
              <el-form-item label="带宽" prop="estimate_bandwidth">
                <el-input type="number"
                  v-model.number="currentDDC_data.estimate_column.estimate_bandwidth"
                />
              </el-form-item>
              <el-form-item label="相关长度" prop="related_len">
                <el-input type="number"
                  v-model.number="currentDDC_data.estimate_column.related_len"
                />
              </el-form-item>
              <el-form-item label="判决门限" prop="judge_threshold">
                <el-input type="number"
                  v-model.number="currentDDC_data.estimate_column.judge_threshold"
                />
              </el-form-item>
              <el-form-item label="插值倍数" prop="up_factor">
                <el-input type="number"
                  v-model.number="currentDDC_data.estimate_column.up_factor"
                />
              </el-form-item>
        </el-form>

        <el-form
              v-else-if="dialog.type === 'data-import'"
              label-width="100px"
            >
              <el-form-item label="Json文件">
                <el-upload
                  ref="uploadRef"
                  action=""
                  drag
                  accept=".json"
                  :limit="1"
                  :auto-upload="false"
                  :file-list="importData.fileList"
                  :on-change="handleFileChange"
                  :on-exceed="handleFileExceed"
                >
                  <el-icon class="el-icon--upload">
                    <i-ep-upload-filled />
                  </el-icon>
                  <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                  </div>
                  <template #tip>
                    <div>Json files</div>
                  </template>
                </el-upload>
              </el-form-item>
        </el-form>
        <template #footer v-if="dialog.type === 'modify'">
            <span class="dialog-footer">
              <el-button @click="confirmModify">确认修改</el-button>
              <el-button @click="cancelModify">取消修改</el-button>
            </span>
        </template>
        <template #footer v-else-if="dialog.type === 'data-import'">
            <span class="dialog-footer">
              <el-button @click="confirmModify" type="primary">确认</el-button>
              <el-button @click="cancelModify">取消</el-button>
            </span>
          </template>
    </el-dialog>
</template>
<script lang="ts" setup>
  import '../assets/font_detect/iconfont.css'
    import { ref, reactive,onMounted, watch,onUnmounted } from 'vue'
    import { ElTable,ElMessage } from 'element-plus'
    import { Download,Upload,Open,TurnOff } from '@element-plus/icons-vue'
    import { genFileId } from 'element-plus'
    import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
    import DetectApi from '../apis/detectHttp.js'
    import CollectApi from '../apis/collectHttp'

    const estimateestimate_algotypes = [{
      value:0,
      label:"FFT"
    },{
      value:1,
      label:"SM求和法"
    },{
      value:2,
      label:"自定义"
    }]
    const uploadRef = ref<UploadInstance>()
    const systemInfo = ref({
        cpu_percent:0,
        field:-1,
        gpu_percent:0,
        memory_percent:0,
        disk_free:0,
        disk_total:0,
        run_path_count:0
    })
    const activeIndex = ref('1')
    const tableData = ref([
    {
      path_id: 0,
      status:3,
    },
    {
      path_id: 1,
      status:0,
    },
    {
      path_id: 2,
      status:0,
    },
    {
      path_id: 3,
      status:0,
    },
    {
      path_id: 4,
      status:0,
    },
    {
      path_id: 5,
      status:0,
    },
    {
      path_id: 6,
      status:0,
    },
    {
      path_id: 7,
      status:0,
    },
    {
      path_id: 8,
      status:1,
    },
    {
      path_id: 9,
      status:0,
    },
    {
      path_id: 10,
      status:0,
    },
    {
      path_id: 11,
      status:0,
    },
    {
      path_id: 12,
      status:0,
    },
    {
      path_id: 13,
      status:0,
    },
    {
      path_id: 14,
      status:0,
    },
    {
      path_id: 15,
      status:0,
    },
    {
      path_id: 16,
      status:0,
    },
    {
      path_id: 17,
      status:0,
    },
    {
      path_id: 18,
      status:0,
    },
    {
      path_id: 19,
      status:0,
    },
    {
      path_id: 20,
      status:0,
    },
    {
      path_id: 21,
      status:0,
    },{
      path_id: 22,
      status:0,
    },{
      path_id: 23,
      status:0,
    }
    ])
    interface oneDDC_data {
        path_id: number
        status: number
        ch0_freq: number
        ch1_freq: number
        ch2_freq: number
        ch3_freq: number
        chid_primary: number
        detect_algotype:number
        burst_count: number
        time_ms: number
    }
    //websocket
  const ws = ref() //socket
  let rec
  let isConnect = false
  let checkMsg = "heartbeat"
  const CreateWebSocket = () => {
    try {
      initWebsocket()
    }catch (e){
      console.log("尝试连接失败");
      // reConnect()
    }
  }
  const initWebsocket = () => {
    const svrHost = window.location.hostname
    let url = "ws://192.168.1.22:8888"
  
    if(svrHost.length < 1)
      url = "ws://192.168.1.22:8888"

    if("WebSocket" in window)
      ws.value = new WebSocket(`ws://${window.location.host}/detectWS`)
    
      ws.value.onopen = () => {
        console.log('[检测ws.onopen]:enter')     
      }

      ws.value.onmessage =  (e) => {
        let data = JSON.parse(e.data)
        if(data && "field" in data) {
          if(data["field"] === 2){
            tableData.value.forEach((item) => {
              if(item.path_id === data["path_id"]){
                item.detect_algotype = data["detect_algotype"]
                item.burst_count = data["burst_count"]
                item.file_count = data["file_count"]
                item.status = data["status"]
                
              }
            })
          }else if(data["field"] === 3){
            tableData.value.forEach((item) => {
              if(item.path_id === data["path_id"]){
                item.status = data["status"]
                item.file_count = data["file_count"]
                item.time_ms = data["time_ms"]
              }
            })
          }else if(data["field"] === 4){
            systemInfo.cpu_percent = data["cpu_percent"]
            systemInfo.disk_free = data["disk_free"]
            systemInfo.disk_total = data["disk_total"]
            systemInfo.gpu_percent = data["gpu_percent"]
            systemInfo.memory_percent = data["memory_percent"]
          }
        }
      }
  
      ws.value.onclose = (e) => {    
        console.log('[检测ws.onclose]: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
        if(e.wasClean) console.log('WebSocket连接已正常关闭'); 
        else ElMessage.error("websocket与检测CS软件连接异常，检测CS软件可能已关闭，尝试重启CS并刷新网页")
      }
    
      ws.value.onerror = (e) => {
        console.log("[检测ws.onerror]:");
        
        // reConnect()
      }
  }
  let reConnect = () => {
    console.log("检测-尝试重新连接");
    if (isConnect) return; //如果已经连上就不在重连了
    rec && clearTimeout(rec);
    rec = setTimeout(function () { // 延迟5秒重连  避免过多次过频繁请求重连
      CreateWebSocket();
    }, 30000);
  }

  //获取系统信息
  const getSystemInfo =async () => {
    const res = await DetectApi.getSysInfo()
    systemInfo.value = res.sys_info
  }
  const getAllDDC = async () => {
    const res = await DetectApi.getAllColumn()
    tableData.value = res.all_column
  }
  const callAllGet = () => {
    getSystemInfo()
    getAllDDC()
  }
  let intervalId = null
  const startPolling = () => {
    intervalId = setInterval(callAllGet, 5000)
  }
  // 停止轮询  
  const stopPolling = () => {  
      clearInterval(intervalId) 
  }
  onMounted(() => {
      getAllDDC()
      startPolling()
      // if(tableData.value.length > 0){
      //   tableData.value.forEach((item) => {
      //     item.ch0_freq.toFixed(6)
      //     item.ch1_freq.toFixed(6)
      //     item.ch2_freq.toFixed(6)
      //     item.ch3_freq.toFixed(6)
      //   })
      // }
  })
    onUnmounted(() => {
      stopPolling()
    })
    const dialog = reactive({
      visible:false,
      type:"singlePath-form",
      width:400,
      title:""
    })  
    const currentDDC_data = ref({
      path_id: 0,
      "collect_column":{ 
        ch0_freq: 81.1,
        ch1_freq: 82.3,
        ch2_freq: 84.6,
        ch3_freq: 90.2,
        sample_rate:96000,
      },
      "detect_column": {
        "chid_primary": 0,
        "detect_algotype": 0,
        "detect_bandwidth": 25000
      },
      "estimate_column": {
        "estimate_algotype": 0,
        "estimate_bandwidth": 25000,
        "freq_range": 8192,
        "judge_threshold": 5,
        "related_len": 50,
        "time_range": 60000,
        "up_factor": 16
      },
    })
    const detect_bandwidths = [{
        value:5000,
        label:"5K"
      },{
        value:25000,
        label:"25K"
    }]
    const detectChannels = [{
      value:0,
      label:"通道0"
    },{
      value:1,
      label:"通道1"
    },{
      value:2,
      label:"通道2"
    },{
      value:3,
      label:"通道3"
    },]

    const detectAlgorithms = [{
      value:0,
      label:"能量检测"
    },{
      value:1,
      label:"相关检测(5k_DAMA)"
    },{
      value:2,
      label:"相关检测(25k_DAMA)"
    },{
      value:3,
      label:"相关检测(CPM)"
    },{
      value:4,
      label:"相关检测(BPSK)"
    },{
      value:5,
      label:"相关检测(QPSK)"
    },{
      value:6,
      label:"相关检测(FSK)"
    }]
    //确认修改
    const confirmModify = () => {
      console.log(currentDDC_data.value) 
      //向服务器提交修改的表格数据
      DetectApi.postModify(currentDDC_data.value)
      dialog.visible = false
    }
    //取消修改
    const cancelModify = () => { 
      dialog.visible = false
    }
    
    //TODO 编辑某行弹出弹窗  
    async function openDialog(type:string,oneColumn:object){
          dialog.visible = true
          dialog.type = type
          
          if(oneColumn.path_id >= 0 && oneColumn.path_id <= 63){
            dialog.title = "修改检测参估参数"
                         
            Object.assign(currentDDC_data.value,{...oneColumn})
          }
    }
    //TODO 停止某行
    async function stopOnePath(id:number) {
      //后端接口发送要停止的DDC通道号,并接收返回的状态更新表格状态栏
      DetectApi.postStop(id)
    }
    //TODO 开始某行
    async function startOnePath(id:number){
      //调用后端接口传要开始的DDC通道号，并接收返回状态更改状态栏显示
      DetectApi.postStart(id)
    }
    //停止当前所有通道的检测
    const stopAll = async () => {
      DetectApi.postStopAll()
    }
    const multiSelection = ref([])//用于加载所有要开始/停止的ID集合
    //处理选择的行改变
    const handleSelectionChange = (selection:any) => {
      multiSelection.value = selection.map((item:any) => item.path_id)
    }
    //TODO 开始多行
    async function startMultiPaths() {
      for(const item in multiSelection.value) console.log(item);
      
    }
    //TODO 停止多行
    async function stopMultiPaths() {
      for(const item in multiSelection.value) console.log(item);
      
    }
    //导出json文件
    const handleExport = async () =>{
      //TODO 调用接口请求配置文件数据
      const fileName = "config.json"
      const fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=uft-8"
      const data = JSON.stringify(tableData.value)
      const blob = new Blob([data],{type:fileType})
      const downloadUrl = window.URL.createObjectURL(blob)
      const downloadLink = document.createElement("a")
      downloadLink.href = downloadUrl
      downloadLink.download = fileName

      document.body.appendChild(downloadLink)
      downloadLink.click()

      document.body.removeChild(downloadLink)
      window.URL.revokeObjectURL(downloadUrl)
    }
    // 用户导入数据
    const importData = reactive({
      deptId: undefined,
      file: undefined,
      fileList: [],
    });

    const handleFileChange = async (file:any) => {
      importData.file = file.raw      
      
    }
    const handleFileExceed = async (files:any) => {
      uploadRef.value!.clearFiles();
      const file = files[0];
      file.uid = genFileId();
      uploadRef.value!.handleStart(file);
      importData.file = file;
    }
</script>

<style>

.systemInfo {
  display: flex;
  margin: 0.2rem 0;
  padding: 0rem 0.4rem;
  height:1.6rem;
  font-size: 0.8rem;
  width: 100%;

  background-color: #909399;
  color: aliceblue;
}
.systemInfo > span {
  flex: 1;
  height: 1.6rem;
  text-align: center;
  justify-content: center;
  align-items: center;
}

</style>